package api

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/gin-gonic/gin"
	"micro-server/middleware"
	mysqlServer "micro-server/modules/mysql"
	"micro-server/router/routerInit"
	"micro-server/vender/article/input"
	"micro-server/vender/article/service"
	"regexp"
	"strings"
)

type Api struct {
}

func RegisterArticle() {
	api := Api{}
	routerInit.ApiNormalGroup.Handle("POST", "article", api.article)
}

func trimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}

func doArticle(html string) (result map[string]string, err error) {
	html = strings.Replace(html, "&lt;", "<", -1)
	html = strings.Replace(html, "&gt;", ">", -1)
	html = strings.Replace(html, "&quot;", `"`, -1)
	htmlRead := strings.NewReader(html)
	htmlDocument, err := goquery.NewDocumentFromReader(htmlRead)
	if err != nil {
		return
	}
	htmlDocument.Find("img").Each(func(i int, s *goquery.Selection) {
		src, _ := s.Attr("src")
		s.Parent().Add("font").SetHtml(fmt.Sprintf("http://www.emakerzone.com%s", src))
	})
	htmlStr, err := htmlDocument.Contents().Html()
	if err != nil {
		return
	}
	key := ""
	oldKey := ""
	result = make(map[string]string, 0)
	m := strings.Split(trimHtml(htmlStr), "\n")
	for _, v := range m {
		if v == "导语" ||
			v == "01" || v == "直播主题" ||
			v == "02" || v == "直播时间" ||
			v == "03" || v == "嘉宾介绍" ||
			v == "04" || v == "直播议题" ||
			v == "05" || strings.Contains(v, "关于") ||
			v == "06" || v == "直播福利" ||
			v == "直播商务合作入口：" {
			if key != "" {
				key = key + " " + v
			} else {
				key = v
			}
			continue
		}
		if key == "" {
			//key = "未知"
			result[oldKey] = result[oldKey] + v
		} else {
			result[key] = v
			oldKey = key
			key = ""
		}
	}
	return
}

func (a *Api) article(gc *gin.Context) {
	params := &input.Article{}
	if err := params.BindingParams(gc); err != nil {
		middleware.ErrorOut(gc, middleware.PARMAS_ERROR, err)
		return
	}

	data, err := service.GetArticle(gc, mysqlServer.BusinessDB, params.Limit)
	if err != nil {
		middleware.ErrorOut(gc, middleware.DATA_NOT_EXIST, err)
		return
	}

	result := make([]map[string]string, 0)
	for _, v := range data {
		if v.Content == "" {
			continue
		}
		d, err := doArticle(v.Content)
		if err != nil {
			continue
		}
		result = append(result, d)
	}

	middleware.SuccessOut(gc, result, middleware.SUCCESS)
	return
}
